package com.kewill.jira.util;

import com.kewill.jira.common.JiraAttribute;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * Created by YanJun on 2016/7/11.
 */
public class ServletUtil {
    public static String getPathInfo(HttpServletRequest request){
        return request.getServletPath().substring(1);
    }

    public static String getActionName(String pathInfo){
        return pathInfo.substring(0,pathInfo.indexOf("."));
    }

    public static HashMap<String,String[]> getParamMap(HttpServletRequest request){
        return (HashMap<String, String[]>) request.getParameterMap();
    }

    public static String getParam(HttpServletRequest request,String key){
        String[] paramvalueArr = getParamMap(request).get(key);
        return paramvalueArr == null ? null : paramvalueArr[0];
    }
    public static void doDownload(File file, HttpServletResponse response)
            throws IOException {
        if (file.exists()) {
            String filename = URLEncoder.encode(file.getName(), "utf-8");
            response.reset();
            response.setContentType("application/x-msdowmload");
            response.addHeader("Content-Disposition", "attachment;filename="+filename);
            FileInputStream  fis = new FileInputStream(file);
            byte[] byteArr = new byte[fis.available()];
            fis.read(byteArr);
            ServletOutputStream out = response.getOutputStream();
            out.write(byteArr);
            out.flush();
            out.close();
        }
    }
}
